﻿using System;
using System.Collections.Generic;
using System.Text;

namespace PengSW.DbfReader
{
    public class DbfReader
    {
        /// <summary>
        /// 初始化参数
        /// </summary>
        /// <param name="aDbfFileName">要读入的Dbf文件名（含路径）</param>
        /// <param name="aSelectSql">要使用的Select语句，可以含有参数，第一个参数是表名，第二个参数是时间戳</param>
        /// <param name="aReadDeletedData">标志是否读入带删除标志的数据</param>
        public DbfReader(string aDbfFileName, string aSelectSql, bool aReadDeletedData)
        {
            m_DbfFileName = aDbfFileName.Trim();
            AnalyFileName();
            SelectSql = aSelectSql.Trim();
            m_ReadDeletedData = aReadDeletedData;
        }

        /// <summary>
        /// 检索参数条件是否已经具备
        /// </summary>
        public bool IsReady
        {
            get
            {
                return m_Path.Length > 0 && m_DbfFileName.Length > 0 && SelectSql.Length>0;
            }
        }

        /// <summary>
        /// 检索Dbf路径
        /// </summary>
        public string Path
        {
            get { return m_Path; }
        }

        public string SelectSql { get; set; }

        /// <summary>
        /// 检索Dbf表名
        /// </summary>
        public string TableName
        {
            get { return m_TableName; }
        }

        /// <summary>
        /// 读取参数指定的Dbf文件到一个DataTable中
        /// </summary>
        /// <returns>结果DataTable</returns>
        public System.Data.DataTable ReadDbf()
        {
            System.Data.DataTable aDataTable = new System.Data.DataTable();

            // 读入DBF文件中的所有记录，包括带删除标记的记录
            string aLocalTimeStamp = string.Empty;
            using (System.Data.Odbc.OdbcConnection aOdbcConnection = new System.Data.Odbc.OdbcConnection(string.Format("Provider=MSDASQL;Driver={{Microsoft Visual FoxPro Driver}};SourceType=dbf;SourceDB={0}", m_Path)))
            {
                aOdbcConnection.Open();
                System.Data.Odbc.OdbcCommand aOdbcCommand = new System.Data.Odbc.OdbcCommand();
                aOdbcCommand.Connection = aOdbcConnection;

                // 设置允许访问删除数据
                if (m_ReadDeletedData)
                {
                    aOdbcCommand.CommandText= "SET DELETED OFF";
                    aOdbcCommand.ExecuteNonQuery();
                }

                // 读入DBF文件到DataTable中
                aLocalTimeStamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                aOdbcCommand.CommandText = string.Format(SelectSql, aLocalTimeStamp, m_TableName);
                using (System.Data.Odbc.OdbcDataAdapter aOdbcAdapter = new System.Data.Odbc.OdbcDataAdapter(aOdbcCommand))
                {
                    aOdbcAdapter.Fill(aDataTable);
                }
                aOdbcConnection.Close();
            }
            return aDataTable;
        }

        /// <summary>
        /// 分析数据文件名，提取路径和表名
        /// </summary>
        private void AnalyFileName()
        {
            System.Text.RegularExpressions.Match aMatch = System.Text.RegularExpressions.Regex.Match(m_DbfFileName, @"^(.+\\)([^\\]+)\.dbf$", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            m_Path = aMatch.Groups[1].Value.Trim();
            m_TableName = aMatch.Groups[2].Value.Trim();
        }

        #region 内部参数

        private string m_DbfFileName;

        private string m_TableName; // 从指定文件名中分析得到Dbf的表名
        private string m_Path;      // 从指定文件名中分析得到Dbf的路径

        private bool m_ReadDeletedData;
        
        #endregion
    }
}
